
const response = require('../utils/response');

const validationMiddleware = (rulesSchema, type = 'body') => async (ctx, next) => {

    const input = type === 'body' ? ctx.request.body : ctx.request.query;


    const schema = rulesSchema[ctx.path];
    if (input === undefined) {
        return response.error(ctx, { message: '请求数据不能为空' });
    }
    if (!schema) {
        return response.error(ctx, { message: '使用但未配置参数rulesSchema' });
    }
    const { error } = schema.validate(input, {
        abortEarly: false,
        allowUnknown: true
    });

    if (error) {
        const errorMessage = error.details.map(detail => detail.message).join(', ');
        return response.error(ctx, { message: errorMessage });
    }

    await next();
};

module.exports = validationMiddleware;


